<template>
  <div class="app">
    <van-nav-bar
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
      :title="DetailData.name"
      placeholder
      fixed
    />

    <div v-html="DetailData.content" class="content"></div>
    <van-action-bar>
      <van-action-bar-icon
        icon="cart-o"
        text="购物车"
        :badge="CartStore.CartTypeNum"
        @click="$router.push('/cart?back=true')"
      />
      <van-action-bar-button type="warning" text="加入购物车" @click="onClickAddCart" />
      <van-action-bar-button type="danger" text="立即购买" @click="onClickBuy" />
    </van-action-bar>
  </div>
</template>

<script setup>
import { useCartStore } from '@/stores/cart'

const CartStore = useCartStore()

import { postAddProductToCartReq } from '@/api/cart'
// import { getProductCommentsReq, getProductDetailReq } from '@/api/Produc'
import {  getProductDetailReq } from '@/api/Produc'
import { ref } from 'vue'
import { useRoute } from 'vue-router'
import { postProToOrderReq } from '@/api/order'
import { getUserInfoReq } from '@/api/user'
let route = useRoute()
let id = route.query.id
//商品信息
let DetailData = ref({})

function getDetailData() {
  getProductDetailReq(id).then((res) => {
    DetailData.value = res.data.data
    console.log(DetailData.value)
  })
}
getDetailData()

//评论
async function getProductComments() {
  // let res = await getProductCommentsReq(id)
  // console.log(res.data,'评论');
}

getProductComments()
//添加购物车
function onClickAddCart() {
  postAddProductToCartReq(DetailData.value.id, 1, DetailData.value.price).then((res) => {
    if (res.data.code == 1) {
      CartStore.getCartList() //更新pinia中购物车列表
      // eslint-disable-next-line no-undef
      showToast('添加购物车成功')
    }
  })
}

// 获取用户信息
let addressStr = ''
let receiver = ''
function getUserInfo() {
  getUserInfoReq().then((res) => {
    console.log(res.data.data)
    receiver = res.data.data.nickName
    addressStr = res.data.data.address.replace(/\//g, '') + res.data.data.area
  })
}
getUserInfo()

//立即购买
function onClickBuy() {
  let products = [{ product: DetailData.value.id, amount: 1 }]
  // console.log(products[0], receiver, addressStr)
  postProToOrderReq(products, receiver, addressStr).then((res) => {
    if (res.data.code == 1) {
      // eslint-disable-next-line no-undef
      showSuccessToast('已添加订单')
    }
    console.log(res.data)
  })
}
</script>

<style lang="scss" scoped>
.app {
  :deep(.content img) {
    width: 100%;
  }
}
</style>
